package com.su.lightthings.utils

import android.content.Context
import android.os.Environment
import android.util.Log
import java.io.File

val TAG = "Suhang"

fun ByteArray.toInt(start: Int, length: Int): Int {
    val subArray = this.copyOfRange(start, start + length)
    var result = 0
    for (i in subArray.indices) {
        result = subArray[i].toInt() or (result shl 8 * i)
    }
    return result
}

fun ByteArray.toUShort(start: Int, length: Int): UShort {
    val subArray = this.copyOfRange(start, start + length)
    return subArray[1].toUByte().toUShort() or (subArray[0].toUByte().toUShort().times(256u).toUShort())
}

/**
 * 将某一段内容转成Long
 */
fun ByteArray.toLong(start: Int, length: Int): Long {
    val subArray = this.copyOfRange(start, start + length)
    var result = 0L
    for (i in subArray.indices) {
        result = (subArray[i].toLong() and 0XFF) or (result shl 8)
    }
    return result
}

fun Byte.getIndex(index: Int): Int {
    return (this.toInt() shr index) and 1
}

fun Byte.getIndexToLong(index: Int): Long {
    return ((this.toInt() shr index) and 1).toLong()
}

fun Int.toByteArray(): ByteArray {
    val byteValue = ByteArray(4)
    byteValue[0] = (this ushr 24 and 0xFF).toByte()
    byteValue[1] = (this ushr 16 and 0xFF).toByte()
    byteValue[2] = (this ushr 8 and 0xFF).toByte()
    byteValue[3] = (this and 0xFF).toByte()
    return byteValue
}

/**
 * 在根目录的Download文件夹创建文件
 */
fun createDownloadFolderFilePath(context: Context?, vararg dirNames: String?): String? {
    val downloadFile = Environment.getExternalStorageDirectory()
    val filePath =
        downloadFile.absolutePath + File.separator + Environment.DIRECTORY_DOWNLOADS + File.separator + "JieLiOTA" + File.separator + "upgrade"
    val file = File(filePath)
    if (!file.exists()) {
        if (!file.mkdirs()) {
            Log.d(TAG, "create dir failed. filePath = $filePath")
        }
    }
    Log.d(TAG, "filePath: $filePath")
    return filePath
}


fun ByteArray.padTo(length: Int): ByteArray {
    return if (this.size >= length) {
        this.copyOf(length)
    } else {
        val paddedArray = ByteArray(length)
        System.arraycopy(this, 0, paddedArray, 0, this.size)
        for (i in this.size until length) {
            paddedArray[i] = 0
        }
        paddedArray
    }
}